package com.dao;

import com.beans.RoleInfo;
import com.jdbc.DBUtil;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;

public class RoleDao {
    public List<RoleInfo> getRoleList(){
        return DBUtil.getList("select * from roleInfo",RoleInfo.class);
    }

    public RoleInfo getRoleInfoById(int roleId) {
        return DBUtil.getSingleObj("select * from roleInfo where id=?",RoleInfo.class,roleId);
    }

    /**
     * 更新某个角色权限
     * @param roleId 角色id
     * @param menuIdList 用户勾选的菜单id列表
     */
    public void updateRoleMenu(int roleId,String[] menuIdList){
        DBUtil.update("delete from roleMenu where roleId=?",roleId);
        for (String menuId: menuIdList){
            DBUtil.update("insert into roleMenu (roleId,menuId) values(?,?)",roleId,menuId);
        }
    }

    /**
     * 根据角色id,得到这角色应该有哪些菜单
     * @param roleId 角色id
     * @return 字符串, 类似  1,3,5,7,9
     */
    public String getMenuIdStr(int roleId) {
        List<Integer> menuIdList=DBUtil.getColumnList("select menuId from roleMenu where roleId=?",Integer.class,roleId);
        String menuIdStr="";
        for(int i=0;i<menuIdList.size();i++) {
            if(i<menuIdList.size()-1) {
                menuIdStr+=menuIdList.get(i)+",";
            }
            else {
                menuIdStr+=menuIdList.get(i);
            }
        }
        return menuIdStr;
    }

    /**
     * 添加角色
     * @param roleInfo 传入一个roleInfo类型参数
     * @return 成功则返回1
     */
    public int addRole(RoleInfo roleInfo) {
        String sql = "insert into roleInfo (roleName,des) values(?,?)";
        Object[] params={
                roleInfo.getRoleName(),
                roleInfo.getDes()
        };
        return DBUtil.update(sql,params);
    }

    /**
     * 更新角色信息
     * @param roleInfo 传入roleInfo类型参数
     * @return 成功则返回1
     */
    public int updateRole(RoleInfo roleInfo) {
        String sql = "update roleInfo set roleName=? ,des=? where id=?";
        return DBUtil.update(sql,roleInfo.getRoleName(),roleInfo.getDes(),roleInfo.getId());
    }

    /**
     * 检查要删除的角色下是否有用户存在
     * @param roleId 传入int型的roleId
     * @return 返回一个RoleInfo对象
     */
    public RoleInfo checkRoleIdUsed(int roleId) {
        return DBUtil.getSingleObj("select * from adminInfo where roleId=?",RoleInfo.class,roleId);
    }

    /**
     * 通过id删除角色
     * @param roleId 传入参数rioleId
     * @return 成功返回1
     */
    public int deleteRoleById(int roleId) {
        return DBUtil.update("delete from roleInfo where Id=?",roleId);
    }


    public RoleInfo checkRoleNameUsed(String roleName) {
        String sql = "select * from roleInfo where roleName=?";
        return DBUtil.getSingleObj(sql,RoleInfo.class,roleName);
    }
}
